package com.maserb.monitor.service.base.impl;

import com.maserb.monitor.service.base.CrudService;
import org.apache.commons.collections4.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

@NoRepositoryBean
public class CrudServiceImpl<Rep extends CrudRepository<T, ID>, T, ID extends Serializable> implements CrudService<Rep, T, ID> {
    @Autowired
    protected Rep repository;

    @Override
    public <S extends T> S save(S var1) {
        return repository.save(var1);
    }

    @Override
    public <S extends T> Iterable<S> save(Iterable<S> var1) {
        return repository.saveAll(var1);
    }

    @Override
    public T findOne(ID var1) {
        return repository.findById(var1).get();
    }

    @Override
    public boolean exists(ID var1) {
        return repository.existsById(var1);
    }

    @Override
    public List<T> findAll() {
        return IteratorUtils.toList(repository.findAll().iterator());
    }

    @Override
    public long count() {
        return repository.count();
    }

    @Override
    public void delete(ID var1) {
        repository.deleteById(var1);
    }

    @Override
    public void delete(T var1) {
        repository.delete(var1);
    }

    @Override
    public void delete(Iterable<? extends T> var1) {
        repository.deleteAll(var1);
    }

    @Override
    public void deleteAll() {
        repository.deleteAll();
    }

    @Override
    @Transactional
    public void deleteAllByKeys(Iterable<? extends ID> var1) {
        var1.forEach(id -> this.repository.deleteById(id));
    }
}
